﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using SyncService.Core.Utils;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Drawing.Printing;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "esb")]
    public class EsbService : SyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<EsbService> _logger = null;

        private bool IsNotPush = false;
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<EsbService>>();
        }
        public EsbService() : base("Esb", "Sap", "")
        {
        }
        public override void Execute(dynamic? state)
        {
            ToClient.Callback = new Action<CallbackData>(YideaClient.CallbackHander);
            RequestData requestData = state;
            var form = requestData.EventId.Substring(0, 3);
             if (form == "com")
            {//处理公司主数据
                DealCompanyData(requestData!.Body);
            }
            else if (form == "cen") { //成本中心
                DealCenterData(requestData!.Body);
            }
        }
        private void DealCenterData(string body)
        {
            try
            {
                List<CenterData> centerList = JsonSerializer.Deserialize<List<CenterData>>(body);
                var customForm = UserDefines.First(x => x.Name == "成本中心");
                var centerCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
                var centerNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
                var companyCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "公司代码");
                var statusField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "状态");
                var isSCSPField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "是否SCSP");
                var CodenameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "代码名称");
                var RegionField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "区域选择");
                foreach (var center in centerList)
                {
                    _logger.LogInformation("DealCenterData ：" + center.CenterCode);
                    List<UserDefinedForm> userdefinedList = YideaClient.GetUserDefinedForms(customForm.Id, new QueryParam() { FilterString = "[{\"field\":\"" + centerCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + center.CenterCode + "\"}]" }).ToList();
                    int isSCSP = 0;
                    if (center.CenterCode.StartsWith("SC") || center.CenterCode.StartsWith("SP"))
                    {
                        isSCSP = 1;
                    }
                    if (userdefinedList.Count > 0)//有就修改
                    {
                        var data = userdefinedList[0];
                        CustomizedFormData customizedFormData1 = new CustomizedFormData();
                        customizedFormData1.FormId = customForm!.Id;
                        customizedFormData1.WebhookPush = false;
                        customizedFormData1.SerialNo = data.SerialNo;
                        JsonObject customizedData1 = new JsonObject();
                        customizedData1.Add(companyCodeField.FieldId, new JsonObject
                        {
                            ["value"] = center.CompanyCode
                        });
                        customizedData1.Add(centerNameField.FieldId, new JsonObject
                        {
                            ["value"] = center.CenterName
                        });
                        customizedData1.Add(statusField.FieldId, new JsonObject
                        {
                            ["value"] = center.Status
                        });
                        customizedData1.Add(isSCSPField.FieldId, new JsonObject
                        {
                            ["value"] = isSCSP
                        });
                        customizedData1.Add(CodenameField.FieldId, new JsonObject
                        {
                            ["value"] = center.CenterCode + " " + center.CenterName
                        });
                        customizedData1.Add(RegionField.FieldId, new JsonObject
                        {
                            ["value"] = center.SectionCode,
                            ["lable"] = center.SectionCode + " " + center.SectionName
                        });
                        customizedFormData1.Data = customizedData1;
                        var updateResponse1 = YideaClient.UpdateCustomizedFormData(customizedFormData1, null);
                    }
                    else
                    { //没有就新增
                        CustomizedFormData customizedFormData1 = new CustomizedFormData();
                        customizedFormData1.StartWorkflow = false;
                        customizedFormData1.TriggerRobot = false;
                        customizedFormData1.FormId = customForm.Id;
                        customizedFormData1.Data = new JsonObject
                        {
                            [centerCodeField.FieldId] = new JsonObject
                            {
                                ["value"] = center.CenterCode.ToString()
                            },
                            [centerNameField.FieldId] = new JsonObject
                            {
                                ["value"] = center.CenterName.ToString()
                            },
                            [companyCodeField.FieldId] = new JsonObject
                            {
                                ["value"] = center.CompanyCode.ToString()
                            },
                            [statusField.FieldId] = new JsonObject
                            {
                                ["value"] = center.Status.ToString()
                            },
                            [isSCSPField.FieldId] = new JsonObject
                            {
                                ["value"] = isSCSP
                            },
                            [CodenameField.FieldId] = new JsonObject
                            {
                                ["value"] = center.CenterCode.ToString() + " " + center.CenterName.ToString()
                            },
                            [RegionField.FieldId] = new JsonObject
                            {
                                ["value"] = center.SectionCode.ToString(),
                                ["lable"] = center.SectionCode.ToString()+ " " + center.SectionName.ToString()
                            },
                        };
                        bool addResult = YideaClient.AddNewCustomizedFormData(customizedFormData1);
                        if (!addResult)
                        {
                            Logger.Info("添加成本中心失败:" + center.CenterCode + "," + center.CompanyCode + "," + center.CenterName + "," + center.Status);
                        }

                    }

                }

                _logger.LogInformation("DealCenterData:结束");
            }
            catch (Exception ex) {
                _logger.LogInformation("DealCenterData error:"+ex.ToString());
            }
        }
        private void DealCompanyData(string body) {
            try
            {
                List<CompanyCustomer> companyList = JsonSerializer.Deserialize<List<CompanyCustomer>>(body);
                var customForm = UserDefines.First(x => x.Name == "公司主数据");
                var companyCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
                var companyNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");
                var currenyCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "货币码");
                var statusField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "状态");
                foreach (var company in companyList)
                {
                    _logger.LogInformation("DealCompanyData:" + company.CompanyCode);
                    List<UserDefinedForm> userdefinedList = YideaClient.GetUserDefinedForms(customForm.Id, new QueryParam() { FilterString = "[{\"field\":\"" + companyCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + company.CompanyCode + "\"}]" }).ToList();
                    if (userdefinedList.Count > 0)//有就修改
                    {
                        var data = userdefinedList[0];
                        CustomizedFormData customizedFormData1 = new CustomizedFormData();
                        customizedFormData1.FormId = customForm!.Id;
                        customizedFormData1.WebhookPush = false;
                        customizedFormData1.SerialNo = data.SerialNo;
                        JsonObject customizedData1 = new JsonObject();
                        customizedData1.Add(companyNameField.FieldId, new JsonObject
                        {
                            ["value"] = company.CompanyName
                        });
                        customizedData1.Add(currenyCodeField.FieldId, new JsonObject
                        {
                            ["value"] = company.CurrencyCode
                        });
                        customizedData1.Add(statusField.FieldId, new JsonObject
                        {
                            ["value"] = company.Status
                        });
                        customizedFormData1.Data = customizedData1;
                        var updateResponse1 = YideaClient.UpdateCustomizedFormData(customizedFormData1, null);
                    }
                    else
                    { //没有就新增
                        CustomizedFormData customizedFormData1 = new CustomizedFormData();
                        customizedFormData1.StartWorkflow = false;
                        customizedFormData1.TriggerRobot = false;
                        customizedFormData1.FormId = customForm.Id;
                        customizedFormData1.Data = new JsonObject
                        {
                            [companyCodeField.FieldId] = new JsonObject
                            {
                                ["value"] = company.CompanyCode.ToString()
                            },
                            [companyNameField.FieldId] = new JsonObject
                            {
                                ["value"] = company.CompanyName.ToString()
                            },
                            [currenyCodeField.FieldId] = new JsonObject
                            {
                                ["value"] = company.CurrencyCode.ToString()
                            },
                            [statusField.FieldId] = new JsonObject
                            {
                                ["value"] = company.Status.ToString()
                            }
                        };
                        bool addResult = YideaClient.AddNewCustomizedFormData(customizedFormData1);
                        if (!addResult)
                        {
                            Logger.Info("添加公司主数据失败:" + company.CompanyCode + "," + company.CompanyName + "," + company.CurrencyCode + "," + company.Status);
                        }

                    }

                }

                _logger.LogInformation("DealCompanyData:结束");
            }
            catch (Exception ex) {
                _logger.LogInformation("DealCompanyData error:" + ex.ToString());
            }
        }
        
    }
}
